package com.zhouheng.springbootactiviti.common.security;


import com.zhouheng.springbootactiviti.common.constants.ActivitiConstants;
import com.zhouheng.springbootactiviti.common.pojo.SecurityUserInfo;
import com.zhouheng.springbootactiviti.common.pojo.SysUser;
import com.zhouheng.springbootactiviti.module.mapper.SysRoleMapper;
import com.zhouheng.springbootactiviti.module.mapper.SysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserMapper sysUserMapper;

    private final SysRoleMapper sysRoleMapper;

    public UserDetailsServiceImpl(SysUserMapper sysUserMapper, SysRoleMapper sysRoleMapper) {
        this.sysUserMapper = sysUserMapper;
        this.sysRoleMapper = sysRoleMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.findByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("数据库中无此用户！");
        }
        List<String> roles = sysRoleMapper.findRoleNameByUserId(sysUser.getId());
        // 操作activiti的api需要拥有ROLE_ACTIVITI_USER角色
        roles.add(ActivitiConstants.ROLE_ACTIVITI_USER);
        return new SecurityUserInfo(sysUser.getUsername(), sysUser.getPassword(), roles);
    }

}
